package com.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingQueue;

/** 采用支持多线程并发访问的集合类型，以及集合数据的循环输出实例 */
public class Lab2withBlockingQueue {
	private LinkedBlockingQueue<String> readDataList;
	// private volatile boolean isFinished=false;

	public static void main(String[] args) {

		Lab2withBlockingQueue lab2 = new Lab2withBlockingQueue();

		lab2.readDataList = new LinkedBlockingQueue<String>();

		lab2.new ReadDataThread().start();

		Thread t2 = lab2.new AnalysisDataThread();
		t2.start();

	}

	class ReadDataThread extends Thread {

		@Override
		public void run() {
			try {
				Scanner sc = new Scanner(new FileInputStream("fdsdata20181025(0623-0624).txt"));

				String line = null;
				while (sc.hasNext()) {
					line = sc.nextLine();
					readDataList.put(line);
				}
				readDataList.put("The end of Data!");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	class AnalysisDataThread extends Thread {

		public void run() {
			/*
			 * 处理数据的线程从集合中提取数据进行处理 while(true) { String line=null; line =
			 * readDataList.take(); if("The end of Data!".equals(line)) break;
			 * //此处可添加处理数据的代码 //。。。。。。。。。。。。。。 System.out.println("Analyzing:"+line);
			 * 
			 * }//end of while
			 * 
			 */

			/*
			 * 输出数据线程的动态输出航显数据的代码参考 建议定义单独定义输出线程类，添加下面的代码
			 */
			while (true) {
				Iterator iterator = readDataList.iterator();
				int i = 0;
				try {
					while (iterator.hasNext()) {
						if (i % 10 == 0) {
							// 输出分屏显示标记
							System.out.println("******************************");
							Thread.sleep(5000);
						} else {
							System.out.println(iterator.next());
						}
						i++;
					}
					// 输出一遍输出结束标记
					System.out.println("——————————————————————————————————————");

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} // end of while

		} // end of run()

	}// end of classAnalysisDataThread

}
